import 'dart:io';

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

class FileUtils {
  /// 获取缓存
  static Future<double> loadApplicationCache() async {
    /// 获取文件夹
    Directory directory = await getApplicationDocumentsDirectory();

    /// 获取缓存大小
    double value = await getTotalSizeOfFilesInDir(directory);
    return value;
  }

  /// 循环计算文件的大小（递归）
  static Future<double> getTotalSizeOfFilesInDir(
      final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children) {
        if (child.path.contains('taskCache')) {
          total += await getTotalSizeOfFilesInDir(child);
        }
      }
      return total;
    }
    return 0;
  }

  /// 缓存大小格式转换
  static String formatSize(double value) {
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  /// 删除缓存
  static void clearApplicationCache() async {
    Directory directory = await getApplicationDocumentsDirectory();
    //删除缓存目录
    await deleteDirectory(directory);
  }

  /// 递归方式删除目录
  static Future<Null> deleteDirectory(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await deleteDirectory(child);
      }
    }
    if (file.path.contains('taskCache') && !file.path.endsWith('taskCache')) {
      List<String> names = file.path.split('/');
      String taskId = names[names.length - 1].split('.')[0];
      await file.delete();
    }
  }

  static void saveDataToFile(
      {required String filePath, required String data}) async {
    if (filePath.isEmpty) {
      return;
    }
    if (data.isEmpty) {
      return;
    }
    final file = File(filePath);
    if (!file.existsSync()) {
      file.createSync(recursive: true);
    }
    final String prevData = await getDataToFile(filePath: filePath);
    Future<File> future = file.writeAsString("$prevData \n $data");
  }

  static Future<String> getDataToFile({required String filePath}) async {
    if (filePath.isEmpty ?? true) {
      return Future.value("");
    }
    try {
      final file = File(filePath);
      return file.readAsString().catchError((e) {});
    } catch (e) {}
    return Future.value("");
  }

  ///获取文件名称，在传入前请做好判空
  static String getFileName(String path) {
    List<String> newPaths = path.split('/');
    return newPaths[newPaths.length - 1];
  }

  ///获取文件类型，在传入前请做好判空
  static String getFileType(String path) {
    List<String> newPaths = path.split('/');
    List<String> newTypes = newPaths[newPaths.length - 1].split('.');
    if (newTypes.length > 1) {
      return newTypes[newTypes.length - 1];
    } else {
      return '';
    }
  }

  ///根据下载链接获取文件名
  static Future<String> getFilePath(String url) async {
    Directory appDocDir = await getApplicationDocumentsDirectory();
    return "${appDocDir.path}/${getFileName(url)}";
  }

  static Future<bool> e(String url) async {
    String path = await getFilePath(url);
    File file = File(path);
    return file.exists();
  }

  static Future<String> downloadFile(String url) async {
    String path = await getFilePath(url);
    Response response = await Dio().download(url, path);
    if (response.statusCode == 200) {
      print('ssss $url下载成功$path');
      return path;
    } else {
      print('ssss $url下载失败${response.statusMessage}');
      return '';
    }
  }
}
